﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IBatisNet.DataMapper;
using pageHelper;
using TempHum.service;
using temphumHis;
using temphumProp;
using WinFormDemo.Helper;

namespace TempHum
{
    public partial class testdata : Form
    {
        private  Form1 form1 = null;
         public static testdata formdata;
        temphumPropdao dao;
        pageLink link ;
        float totalPage;
        float X;
        float Y;
        public testdata(Form1 form1)
        {
            InitializeComponent();
            this.Resize += new System.EventHandler(this.testdata_Resize);
            dao  = new temphumPropdao(Mapper.Instance());
             link = new pageLink();
            comboBox1.SelectedIndex = 0;
            initQuery();
            this.form1 = form1;          
            formdata = this;
            X = this.Width;
            Y = this.Height;
            ResizeForm.setTag(this);
            float  newx = form1.Width/X;
            float newy = form1.Height/Y;
            //   ResizeForm.setControls(newx, newy, this);
            if (this != null)
            {
                ResizeForm.setControls(newx, newy, this);
            }
            this.Width = form1.Width;
            this.Height = form1.Height;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            initQuery();
            loaddata();
        }

        private void textBox9_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox10_TextChanged(object sender, EventArgs e)
        {

        }

        private void searchCondition_Enter(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            compareTime((DateTimePicker)sender);
        }

        private void testdata_Load(object sender, EventArgs e)
        {
                     

        }

        private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
        {
            compareTime((DateTimePicker)sender);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           initQuery();
           link.size = Convert.ToInt32(comboBox1.SelectedItem);
            loaddata();
        }

        private void loaddata() {
            Console.WriteLine(link);
            IList<temphumHisData> list = dao.findByPaginated(link);
             dataGridView1.AutoGenerateColumns = false;
         //   dataGridView1.AllowUserToResizeColumns = true;
        //    dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            this.dataGridView1.DataSource = list;
            if (dataGridView1.Columns.Contains("id"))
            {
                dataGridView1.Columns["id"].Visible = false;
            }
            if (dataGridView1.Columns.Contains("testcount"))
            {
                dataGridView1.Columns["testcount"].Visible = false;
            }
            if (link.producttype == 1)
            {
                dataGridView1.Columns[9].Visible = false;
                dataGridView1.Columns[10].Visible = false;
                dataGridView1.Columns[11].Visible = false;
                dataGridView1.Columns[12].Visible = false;
            }
            else {
                dataGridView1.Columns[9].Visible = true;
                dataGridView1.Columns[10].Visible = true;
                dataGridView1.Columns[11].Visible = true;
                dataGridView1.Columns[12].Visible = true;
            }
           // this.dataGridView1.Columns.Remove("testcount");
            this.dataGridView1.Refresh();
            Console.WriteLine(link);
         long count =  dao.findHisDataCount(link);
            textBox4.Text = count + "";
            textBox2.Text = link.page+"";          
            if (count % link.size != 0)
            {
                totalPage = (count / link.size) + 1;
            }
            else {
                totalPage = (count / link.size);
            }
            if (link.page == 1) { button1.Enabled =  button2.Enabled = false; } else { button1.Enabled = button2.Enabled = true; }
            if (link.page == totalPage) {button3.Enabled = button4.Enabled = false; }else { button3.Enabled = button4.Enabled = true; }
            textBox3.Text = totalPage + "";
        }
        private void initQuery() {
            link.page = 1;
            link.serialnumber = textBox9.Text;
            link.testport = textBox10.Text;
            link.starttime = dateTimePicker1.Value.Date + dateTimePicker3.Value.TimeOfDay;
            link.endtime = dateTimePicker2.Value.Date + dateTimePicker4.Value.TimeOfDay;
            link.size = Convert.ToInt32(comboBox1.SelectedItem);
            if (comboBox2.SelectedIndex == 0) link.result = null;
            else link.result = comboBox2.SelectedItem.ToString();
            if (comboBox3.SelectedIndex == 0) link.producttype = null;
            else link.producttype = comboBox3.SelectedIndex - 1;
            button1.Enabled = button2.Enabled = false;
            button3.Enabled = button4.Enabled = false;
        }

        private void dateTimePicker3_ValueChanged(object sender, EventArgs e)
        {
            compareTime((DateTimePicker)sender);
        }
        private void compareTime(DateTimePicker d) {
            DateTime starttime = dateTimePicker1.Value.Date + dateTimePicker3.Value.TimeOfDay;
            DateTime endtime = dateTimePicker2.Value.Date + dateTimePicker4.Value.TimeOfDay;
            if (DateTime.Compare(starttime, endtime) > 0)
            {
                MessageBoxEx.Show(this, "起始时间不能大于截至时间！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                d.Value = link.starttime;
                return;
            }
            link.starttime = dateTimePicker1.Value.Date + dateTimePicker3.Value.TimeOfDay;
            link.endtime = dateTimePicker2.Value.Date + dateTimePicker4.Value.TimeOfDay;
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            compareTime((DateTimePicker)sender);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            link.page = 1;
            loaddata();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            link.page = link.page -1;
            loaddata();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            link.page = link.page + 1;
            loaddata();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            link.page = (int)totalPage;
            loaddata();
        }

        private void 测试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            this.form1.Visible = true;
        }

        private void testdata_closing(object sender, FormClosingEventArgs e)
        {
            formdata.Dispose();
            this.form1.Visible = true;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            // 添加数据导出功能
            string fileName = "LEFOO_TestData_";//可以在这里设置默认文件名
            string saveFileName = "";//文件保存名
            SaveFileDialog saveDialog = new SaveFileDialog();//实例化文件对象
            saveDialog.DefaultExt = "xlsx";//文件默认扩展名
            saveDialog.Filter = "Excel文件|*.xlsx";//获取或设置当前文件名筛选器字符串，该字符串决定对话框的“另存为文件类型”或“文件类型”框中出现的选择内容。
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();//打开保存窗口给你选择路径和设置文件名
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，您的电脑可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;//Workbooks代表一个 Microsoft Excel 工作簿
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);//新建一个工作表。 新工作表将成为活动工作表。
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
                                                                                                                                  //写入标题   
            pageLink pageLink = link;
                for (int j = 1; j <= totalPage; j++)
                {
                    pageLink.page = j;
                    IList<temphumHisData> list = dao.findByPaginated(link);
                    for (int k = 0; k < list.Count; k++)
                    {
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)//遍历循环获取DataGridView标题
                    {
                        if (j == 1)
                        {
                            worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                        }
                        worksheet.Cells[(j-1)*link.size+k + 2, i + 1] = list[k].GetType().GetProperty(dataGridView1.Columns[i].DataPropertyName).GetValue(list[k]);
                        System.Windows.Forms.Application.DoEvents();//实时更新表格
                    }
                   
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
                
            }// worksheet.Cells[1, i + 1]表示工作簿第一行第i+1列，Columns[i].HeaderText表示第i列的表头
            MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);//提示保存成功
            try
            {
                workbook.Saved = true;//获取或设置一个值，该值指示工作簿自上次保存以来是否进行了更改
                workbook.SaveCopyAs(saveFileName);  //fileSaved = true;将工作簿副本保存到文件中，但不修改内存中打开的工作簿                 
            }
            catch (Exception ex)
            {//fileSaved = false;                      
                MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
            }
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex == 0) link.result = null;
            else link.result = comboBox2.SelectedItem.ToString();
        }

        private void testdata_Resize(object sender, EventArgs e)
        {
            float newx = this.Width / X;
            float newy = this.Height / Y;
            if (this != null)
            {
                ResizeForm.setControls(newx, newy, this);
            }
            //  ResizeForm.setControls(newx, newy, this);
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            Console.WriteLine("e.RowIndex" + e.RowIndex);
            if (e.RowIndex > -1) {
              String result =  this.dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
                if (result == "NG")
                {
                    this.dataGridView1.Rows[e.RowIndex].Cells[4].Style.BackColor = Color.Red;
                }
                else {
                    this.dataGridView1.Rows[e.RowIndex].Cells[4].Style.BackColor = Color.Green;
                }
            }
           
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex == 0) link.producttype = null;
            else link.producttype = comboBox3.SelectedIndex - 1;
        }
    }
}
